<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';


function getRandAddress() {
	$ip_long = [
		['607649792', '608174079'], //36.56.0.0-36.63.255.255
		['1038614528', '1039007743'], //61.232.0.0-61.237.255.255
		['1783627776', '1784676351'], //106.80.0.0-106.95.255.255
		['2035023872', '2035154943'], //121.76.0.0-121.77.255.255
		['2078801920', '2079064063'], //123.232.0.0-123.235.255.255
		['-1950089216', '-1948778497'], //139.196.0.0-139.215.255.255
		['-1425539072', '-1425014785'], //171.8.0.0-171.15.255.255
		['-1236271104', '-1235419137'], //182.80.0.0-182.92.255.255
		['-770113536', '-768606209'], //210.25.0.0-210.47.255.255
		['-569376768', '-564133889'], //222.16.0.0-222.95.255.255
	];
	$rand_key = mt_rand(0, 9);
	return long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
}

function getCampaigns($url, $data, $ip, $cookie) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_POST, true );
	curl_setopt ( $ch, CURLOPT_HEADER, false);
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
	curl_setopt ( $ch, CURLOPT_COOKIE, $cookie);
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, [
		'CLIENT-IP: '.$ip,
		'X-FORWARDED-FOR: '.$ip,
		'content-type: application/json;charset=UTF-8',
		'referer: https://pro.xiaohongshu.com/ares/advertising/microapp/unify-search',
		'user-agent: Mozilla/5.0 (Windows NT '. mt_rand(8, 10) .'.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'. mt_rand(10, 90) .'.0.4240.'. mt_rand(10, 90) .' Safari/'.mt_rand(100, 700).'.36',
	]);
	$string = curl_exec ( $ch );
	curl_close ($ch );
	return $string;
}

run(function() use ($argv) {

	showMessage('获取小红书数据.' );
 	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `username`, `password`, `token`, `bazaarId`, `regionTarget` as `cookie` FROM cfg_expand where status = 1 and userType = 10');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

  foreach ($userList as $value) {
		if ( $value['cookie'] ) {
			$ip = getRandAddress();
			showMessage($value['username'].'获取小红书昨天数据.' );
			$doResponse = getCampaigns('https://pro.xiaohongshu.com/api/eros/rtb/campaigns/index', json_encode([
				'start_time'=> date("Y-m-d 00:00:00", strtotime("-1 day")),
				'end_time'=> date("Y-m-d 23:59:59", strtotime("-1 day")),
				'filter_state'=> 6,
				'marketing_target'=> -1,
				'name'=> "",
				'page_index'=> 1,
				'page_size'=> 20,
				'search_column'=>2,
			]), $ip, $value['cookie']);
			$jsondata = json_decode($doResponse, true);
			if(is_array($jsondata)) {
				if(isset($jsondata['data']['aggregation_data'])) {
					// 展现量
					$impression_str = isset($jsondata['data']['aggregation_data']['impression_str']) ? $jsondata['data']['aggregation_data']['impression_str'] : 0;
					// 点击量
					$click_str = isset($jsondata['data']['aggregation_data']['click_str']) ? $jsondata['data']['aggregation_data']['click_str'] : 0;
					// 消费
					$spent_str = isset($jsondata['data']['aggregation_data']['spent_str']) ? $jsondata['data']['aggregation_data']['spent_str'] : 0;
					// 点击率
					$ctr_str = isset($jsondata['data']['aggregation_data']['ctr_str']) ? rtrim($jsondata['data']['aggregation_data']['ctr_str'], '%') : 0;
					// 平均点击价
					$acp_str = isset($jsondata['data']['aggregation_data']['acp_str']) ? $jsondata['data']['aggregation_data']['acp_str'] : 0;
					// 昨天的数据
					$datetime = date("Y-m-d 01:00:00", strtotime("-1 day"));
					$res = $database->query("select id from cfg_xhs where `companyId` = '{$value['companyId']}' AND `username` = '{$value['username']}' AND to_days(`datetime`) = to_days('{$datetime}') LIMIT 1");
					$database->query( " UPDATE cfg_expand SET `userStat` = '1', `lastDatetime` = NOW() WHERE id = '{$value['id']}'; ");
					if( isset($res[0]['id']) ) {
						$database->query( " UPDATE cfg_xhs SET `spent_str` = '{$spent_str}', `bazaarId` = '{$value['bazaarId']}', `impression_str` = '{$impression_str}',
						`click_str` = '{$click_str}', `ctr_str` = '{$ctr_str}', `acp_str` = '{$acp_str}', `update` = NOW() WHERE id = '{$res[0]['id']}'; ");
					} else {
						$database->query("INSERT INTO cfg_xhs ( `companyId`, `username`, `bazaarId`, `spent_str`, `impression_str`, `click_str`, `ctr_str`, `acp_str`, `datetime`, `update` ) values
							( '{$value['companyId']}', '{$value['username']}', '{$value['bazaarId']}', '{$spent_str}', '{$impression_str}', '{$click_str}', '{$ctr_str}', '{$acp_str}', '{$datetime}', NOW() ) " );
					}
				} else {
					$database->query( " UPDATE cfg_expand SET `userStat` = '2', `lastDatetime` = NOW() WHERE id = '{$value['id']}'; ");
				}
			}

			showMessage($value['username'].'获取小红书今天数据.' );
			$doResponse = getCampaigns('https://pro.xiaohongshu.com/api/eros/rtb/campaigns/index', json_encode([
				'start_time'=> date("Y-m-d 00:00:00"),
				'end_time'=> date("Y-m-d 23:59:59"),
				'filter_state'=> 6,
				'marketing_target'=> -1,
				'name'=> "",
				'page_index'=> 1,
				'page_size'=> 20,
				'search_column'=>2,
			]), $ip, $value['cookie']);
			$jsondata = json_decode($doResponse, true);
			if(is_array($jsondata)) {
				if(isset($jsondata['data']['aggregation_data'])) {
					// 展现量
					$impression_str = isset($jsondata['data']['aggregation_data']['impression_str']) ? $jsondata['data']['aggregation_data']['impression_str'] : 0;
					// 点击量
					$click_str = isset($jsondata['data']['aggregation_data']['click_str']) ? $jsondata['data']['aggregation_data']['click_str'] : 0;
					// 消费
					$spent_str = isset($jsondata['data']['aggregation_data']['spent_str']) ? $jsondata['data']['aggregation_data']['spent_str'] : 0;
					// 点击率
					$ctr_str = isset($jsondata['data']['aggregation_data']['ctr_str']) ? rtrim($jsondata['data']['aggregation_data']['ctr_str'], '%') : 0;
					// 平均点击价
					$acp_str = isset($jsondata['data']['aggregation_data']['acp_str']) ? $jsondata['data']['aggregation_data']['acp_str'] : 0;
					// 今天的数据
					$datetime = date("Y-m-d 01:00:00");
					$res = $database->query("select id from cfg_xhs where `companyId` = '{$value['companyId']}' AND `username` = '{$value['username']}' AND to_days(`datetime`) = to_days('{$datetime}') LIMIT 1");
					$database->query( " UPDATE cfg_expand SET `userStat` = '1', `lastDatetime` = NOW() WHERE id = '{$value['id']}'; ");
					if( isset($res[0]['id']) ) {
						$database->query( " UPDATE cfg_xhs SET `spent_str` = '{$spent_str}', `bazaarId` = '{$value['bazaarId']}', `impression_str` = '{$impression_str}', `click_str` = '{$click_str}', `ctr_str` = '{$ctr_str}', `acp_str` = '{$acp_str}', `update` = NOW() WHERE id = '{$res[0]['id']}'; ");
					} else {
						$database->query("INSERT INTO cfg_xhs ( `companyId`, `username`, `bazaarId`, `spent_str`, `impression_str`, `click_str`, `ctr_str`, `acp_str`, `datetime`, `update` ) values
							( '{$value['companyId']}', '{$value['username']}', '{$value['bazaarId']}', '{$spent_str}', '{$impression_str}', '{$click_str}', '{$ctr_str}', '{$acp_str}', '{$datetime}', NOW() ) " );
					}
				} else {
					$database->query( " UPDATE cfg_expand SET `userStat` = '2', `lastDatetime` = NOW() WHERE id = '{$value['id']}'; ");
				}
			}
		}
	}

});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');